import Vue from 'vue';

/**
 * @description select下拉框滚动到底部触发事件
 * @param {String} loadmore 自定义的指令名称，使用方法：v-loadmore = "func or data"
 */
Vue.directive('loadmore', {
  bind(el, binding) {
    Vue.nextTick(() => {
      const querySelectorName = binding.arg
        ? `.${binding.arg} .el-select-dropdown .el-select-dropdown__wrap`
        : '.el-select-dropdown .el-select-dropdown__wrap';
      const SELECTWRAP_DOM = el.querySelector(querySelectorName);
      if (!SELECTWRAP_DOM) return;
      let lastTimestamp = null;
      el.loadmore = function () {
        // 判断滚动到底部 this.clientHeight+100 用<=会触发很多遍 用===
        const CONDITION =
          Math.floor(this.scrollHeight - this.scrollTop) <=
          this.clientHeight + 1;
        if (CONDITION) {
          if (lastTimestamp && new Date().getTime() - lastTimestamp < 50) {
            return;
          }
          binding.value();
          lastTimestamp = new Date().getTime();
        }
      };
      SELECTWRAP_DOM.addEventListener('scroll', el.loadmore);
      el.SELECTWRAP_DOM = SELECTWRAP_DOM;
    });
  },
  unbind(el) {
    if (!el.SELECTWRAP_DOM) return;
    el.SELECTWRAP_DOM.removeEventListener('scroll', el.loadmore);
    el.loadmore = null;
    el.SELECTWRAP_DOM = null;
  }
});

// 自定义埋点指令
Vue.directive('track', {
  bind: (el, binding) => {
    el._setTrack = () => {
      Vue.prototype.$trackHandler(binding.value);
    };
    el.addEventListener('click', el._setTrack);
  },
  unbind: el => {
    el.removeEventListener('click', el._setTrack);
    delete el._setTrack;
  }
});
